using UnityEngine;
using Delta2DGame.Base;

namespace Delta2DGame.State
{
    /// <summary>
    /// 敌人巡逻状态
    /// </summary>
    public class PatrolState : EnemyState
    {
        [SerializeField] private Transform[] patrolPoints;
        [SerializeField] private float moveSpeed = 2f;
        [SerializeField] private float attackRange = 3f;
        [SerializeField] private float waitTime = 1f;

        private int currentPointIndex = 0;
        private float waitTimer = 0f;
        private Vector3 originalPosition;

        public PatrolState(EnemyStateMachine stateMachine, EnemyController enemy, string animBoolName)
            : base(stateMachine, enemy, animBoolName)
        {
            originalPosition = enemy.transform.position;
            // 获取巡逻点（假设巡逻点已在Inspector中分配）
            patrolPoints = enemy.GetComponent<EnemyPatrolPoints>().points;
        }

        public override void Enter()
        {
            base.Enter();
            currentPointIndex = 0;
            waitTimer = 0f;
        }

        public override void Update()
        {
            base.Update();

            // 检测玩家是否在攻击范围内
            if (IsPlayerInAttackRange())
            {
                stateMachine.SwitchState(stateMachine.attackState);
                return;
            }

            // 如果远离初始位置，返回原位
            if (Vector2.Distance(enemy.transform.position, originalPosition) > 10f)
            {
                stateMachine.SwitchState(stateMachine.returnState);
                return;
            }

            // 如果有巡逻点，则移动到下一个巡逻点
            if (patrolPoints != null && patrolPoints.Length > 0)
            {
                MoveToPatrolPoint();
            }
        }

        private void MoveToPatrolPoint()
        {
            Transform targetPoint = patrolPoints[currentPointIndex];
            enemy.transform.position = Vector2.MoveTowards(
                enemy.transform.position,
                targetPoint.position,
                moveSpeed * Time.deltaTime
            );

            // 到达巡逻点后等待
            if (Vector2.Distance(enemy.transform.position, targetPoint.position) < 0.1f)
            {
                waitTimer += Time.deltaTime;
                if (waitTimer >= waitTime)
                {
                    currentPointIndex = (currentPointIndex + 1) % patrolPoints.Length;
                    waitTimer = 0f;
                }
            }
        }

        private bool IsPlayerInAttackRange()
        {
            GameObject player = GameObject.FindGameObjectWithTag("Player");
            if (player != null)
            {
                float distance = Vector2.Distance(enemy.transform.position, player.transform.position);
                return distance <= attackRange;
            }
            return false;
        }
    }
}